/**
 * 猎头公司设置
 * */
import React from 'react';
import { Modal, Input, Form, message, Spin, Select } from 'antd';
import FileUpload from '@/components/Custom/FileUpload';
import { connect } from 'umi';
import { getEmployeeInfoList } from '@/services/components/userform';
import { useRequest } from '@/hooks';
import MultipleInput from '../MultipleInput';
import { transformFileList } from '../../../utils';
import { addHuntingChannel, updateHuntingChannel } from '../../service';

const formItemLayout = {
    labelCol: {
        sm: { span: 7 }
    },
    wrapperCol: {
        sm: { span: 14 }
    }
};

const CompanyModal = ({ form, data, onSuccess, children }) => {
    const { getFieldDecorator } = form;
    const [visible, setVisible] = React.useState(false);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [readyFlag, setReadyFlag] = React.useState(false);
    const firstRef = React.useRef(true);
    const employeeRef = React.useRef(null);

    // 搜索人员
    const {
        data: employeeList,
        loading: employeeLoading,
        run: fetchEmployeeList,
        mutate: setEmployeeList
    } = useRequest(
        tagName =>
            getEmployeeInfoList({
                name: tagName
            }),
        {
            debounceInterval: 500,
            manual: true,
            initialData: [],
            formatResult: res => {
                if (res) {
                    firstRef.current = false;
                    const { code, data: resData, msg } = res;
                    if (code === 10000) {
                        if (!employeeRef.current) {
                            employeeRef.current = resData;
                        }
                        return resData;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );
    const handleSearch = _value => {
        if (_value) {
            fetchEmployeeList(_value.trim());
        }
    };

    React.useEffect(() => {
        if (visible && employeeList?.length === 0) {
            fetchEmployeeList();
        }
        if (!visible) {
            form.resetFields();
        }
    }, [visible]);
    const handleEmployeeFocus = () => {
        if (employeeRef.current) {
            setEmployeeList(employeeRef.current);
        }
    };
    // 确定
    const handleOk = () => {
        form.validateFields((err, values) => {
            // console.log('handleOk -> values', values);
            if (!err) {
                const {
                    acceptKeys = [],
                    acceptEmails = [],
                    sendKeys = [],
                    sendEmails = [],
                    resourceRelation,
                    ...rest
                } = values;
                const acceptRecruitEmails = acceptKeys.map(k => acceptEmails?.[k]);
                const channelEmails = sendKeys.map(k => sendEmails?.[k]);
                const params = {
                    ...rest,
                    acceptRecruitEmails,
                    channelEmails,
                    resourceRelation: resourceRelation?.uploadResourceFile ? [resourceRelation?.uploadResourceFile] : []
                };
                // console.log('handleOk -> params', params);
                setSubmitLoading(true);
                if (data) {
                    updateHuntingChannel({
                        ...params,
                        channelId: data.id
                    })
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                message.success('操作成功');
                                if (onSuccess) {
                                    onSuccess();
                                }
                                setVisible(false);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    addHuntingChannel(params)
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                message.success('操作成功');
                                if (onSuccess) {
                                    onSuccess();
                                }
                                setVisible(false);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                }
            }
        });
    };

    React.useEffect(() => {
        if (!data || !visible) {
            return;
        }
        const {
            acceptRecruitEmails = [],
            channelEmails = [],
            recruitChannelLogoFile = [],
            channelName,
            channelLinkName,
            channelLinkTel
        } = data;
        const finalFieldsValue = {
            channelName,
            channelLinkName,
            channelLinkTel,
            acceptEmails: acceptRecruitEmails,
            sendEmails: channelEmails,
            resourceRelation: transformFileList(recruitChannelLogoFile || [])
        };
        // console.log('CompanyModal -> finalFieldsValue', finalFieldsValue);
        if (!readyFlag) {
            setReadyFlag(true);
        } else {
            form.setFieldsValue(finalFieldsValue);
        }
    }, [data, visible, readyFlag]);

    // 取消
    const handleCancel = () => {
        setVisible(false);
    };

    // 显示modal
    const handleModal = () => {
        setVisible(true);
    };

    const handleAfterClose = () => {
        form.resetFields();
    };

    return (
        <>
            <div onClick={handleModal}>{children}</div>
            <Modal
                title={data ? '编辑猎头公司' : '新增猎头公司'}
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
                width={640}
                confirmLoading={submitLoading}
                afterClose={handleAfterClose}
            >
                <Form {...formItemLayout} labelAlign="right" style={{ paddingTop: '30px' }}>
                    <Form.Item label="猎头名称">
                        {getFieldDecorator('channelName', {
                            rules: [{ required: true, message: '请输入猎头名称' }]
                        })(<Input placeholder="请输入猎头名称" maxLength={20} />)}
                    </Form.Item>
                    <Form.Item label="接收需求邮箱" required>
                        <MultipleInput
                            prefix="accept"
                            form={form}
                            placeholder="请输入接收需求邮箱"
                            initialValue={data?.acceptRecruitEmails?.map((_, index) => index) || undefined}
                        />
                    </Form.Item>
                    <Form.Item label="发送简历邮箱" required>
                        <MultipleInput
                            prefix="send"
                            form={form}
                            placeholder="请输入发送简历邮箱"
                            initialValue={data?.channelEmails?.map((_, index) => index) || undefined}
                        />
                    </Form.Item>
                    <Form.Item label="授权用户">
                        <Spin spinning={firstRef.current && employeeLoading}>
                            {getFieldDecorator('authEmployeeCodes', {
                                initialValue: data
                                    ? data?.channelAccountAuthVOList?.map(item => item.authEmployeeCode)
                                    : []
                            })(
                                <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    placeholder="请选择授权用户"
                                    allowClear
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                    onFocus={handleEmployeeFocus}
                                    onSearch={handleSearch}
                                    filterOption={false}
                                >
                                    {employeeList?.map(item => (
                                        <Select.Option value={item.employeeCode} key={item.employeeCode}>
                                            {item.employeeName}
                                        </Select.Option>
                                    ))}
                                </Select>
                            )}
                        </Spin>
                    </Form.Item>
                    <Form.Item label="联系人姓名">
                        {getFieldDecorator('channelLinkName')(<Input placeholder="请输入联系人姓名" maxLength={20} />)}
                    </Form.Item>
                    <Form.Item label="联系人电话">
                        {getFieldDecorator('channelLinkTel')(<Input placeholder="请输入联系人电话" maxLength={20} />)}
                    </Form.Item>
                    <Form.Item label="渠道logo" style={{ marginBottom: 0 }}>
                        <div style={{ height: 102 }}>
                            {getFieldDecorator('resourceRelation')(
                                <FileUpload
                                    isSingle
                                    checkFileSize={1}
                                    checkFileSizeMsg="文件大小不能超过1MB！"
                                    categoryCode="recruitChannelLogoFile"
                                    checkFileType="JPG,JPEG,BMP,PNG"
                                    checkFileTypeMsg="只能上传JPG,JPEG,BMP,PNG格式的文件！"
                                />
                            )}
                        </div>
                        <span>支持bmp、jpg、png格式，大小不可超过1M</span>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(CompanyModal));
